<template lang="html">
	<div class="container">
		<!-- :center="[106.877303, 26.720362]" 乌当区中心点-->
		<!-- :center="[106.69719, 26.46128]" 小河中心点 -->
		<!-- 地图区域 -->
		<div id="amapBox3d"></div>
		<img src="../../static/pic/bk1.png" style="width: 100%;height: 100%;position: absolute;left: 0;top: 0;pointer-events: none;" />
		<div style="display: none;">
			<info-window ref="infoWindowRef" :projectInfo="projectInfo" @close="close"></info-window>
		</div>
	</div>
</template>

<script>
	import infoWindow from '../components/AmapInfoWindow/index.vue';
	// import {
		// geoJSON
	// } from '../../../static/xiaohe.js';
	export default {
		components: {
			infoWindow
		},
		name: 'AMap',
		props: {
			projectInfoVOList: {
				type: Array,
				default: () => {
					return [];
				}
			}
		},
		data() {
			let self = this;
			return {
				object3Dlayer: null,
				modelsList: [],
				object: null,
				line3DList: [],
				map: null,
				jsq: null,
				infoWindow: null,
				projectList: [],
				projectInfo: {},
				// geoJSON,
				zhengli_build: [{
					center: [106.709137, 26.453225],
					modelInfo: {
						url: '/static/models/ludeng',
						rotate: 40, //模型旋转角度（主要是给塔机用的）
						jindu: 1, //模型进度
						scale: 1 //模型缩放
					},
					info: {
						name: '路灯A',
						hjjc: true,
						wifi: true,
						led: true,
						aiVideo: true,
						cityFM: true,
						car_power: true,
						phone_power: true,
						ad: true,
					}
				}, {
					center: [106.709585, 26.452329],
					modelInfo: {
						url: '/static/models/ludeng',
						rotate: 40, //模型旋转角度（主要是给塔机用的）
						jindu: 1, //模型进度
						scale: 1 //模型缩放
					},
					info: {
						name: '路灯B',
						hjjc: true,
						wifi: true,
						led: true,
						aiVideo: true,
						cityFM: true,
						car_power: true,
						phone_power: true,
						ad: true,
					}
				}, {
					center: [106.709709, 26.453467],
					modelInfo: {
						url: '/static/models/ludeng',
						rotate: 40, //模型旋转角度（主要是给塔机用的）
						jindu: 1, //模型进度
						scale: 1 //模型缩放
					},
					info: {
						name: '路灯C',
						hjjc: true,
						wifi: true,
						led: true,
						aiVideo: true,
						cityFM: true,
						car_power: true,
						phone_power: true,
						ad: true,
					}
				}, {
					center: [106.710272, 26.454403],
					modelInfo: {
						url: '/static/models/ludeng',
						rotate: 40, //模型旋转角度（主要是给塔机用的）
						jindu: 1, //模型进度
						scale: 1 //模型缩放
					},
					info: {
						name: '路灯D',
						hjjc: true,
						wifi: true,
						led: true,
						aiVideo: true,
						cityFM: true,
						car_power: true,
						phone_power: true,
						ad: true,
					}
				}, ]
			};
		},
		watch: {
			projectInfoVOList: {
				handler(val) {
					this.projectList = [];
					if (val.length !== 0) {
						setTimeout(() => {
							for (var i = 0; i < val.length; i++) {
								var item = val[i];
								this.projectList.push({
									id: item.id,
									position: [Number(item.position[0]), Number(item.position[1])],
									visible: false,
									content: '',
									info: {
										name: item.name,
										projectStatus: item.projectStatus,
										stand: item.stand,
										isAcc: item.isAcc,
										isAtt: item.isAtt,
										isBond: item.isBond,
										isCon: item.isCon,
										isEnough: item.isEnough,
										isIns: item.isIns,
										isSaf: item.isSaf,
										isWages: item.isWages,
									}
								});
							}
						}, 100);
					}
				},
				deep: true,
				immediate: true
			}
		},
		mounted() {
			setTimeout(() => {
				this.init()
			}, 1000);
		},
		methods: {
			init(center, zoom) {
				this.map = new AMap.Map('amapBox3d', {
					mapStyle: 'amap://styles/darkblue',
					viewMode: '3D',
					showBuildingBlock: true,
					center: center ? center : [106.708999, 26.453174],
					showLabel: false,
					pitchEnable: true,
					skyColor: '#000928',
					expandZoomRange: true,
					zoom: 20,
					pitch: 65,
				});
				setInterval(() => {
					this.map.setRotation((this.map.getRotation() + 0.06) % 360);
				}, 10);
				this.map.on('click', ev => {
					console.log([ev.lnglat.lng, ev.lnglat.lat])
				})
				//加载其他因素，包括模型、marker、图标、气球
				for (var i = 0; i < this.zhengli_build.length; i++) {
					var item = this.zhengli_build[i];
					this.zhengli_loadModel(item.center[0], item.center[1], item.modelInfo.url, item.modelInfo.rotate, item.modelInfo.jindu,
						item.modelInfo.scale);

					this.zhengli_loadPoints(item.center[0], item.center[1], '/static/pic/ludeng.png', 200, item.info, [0.23529,
						0.70196, 0.44314, 1
					])
				}

				// var geojson = new AMap.GeoJSON({
				// 	geoJSON: this.geoJSON.features,
				// 	// 还可以自定义getMarker和getPolyline
				// 	getPolygon: function(geojson, lnglats) {
				// 		// 计算面积
				// 		var area = AMap.GeometryUtil.ringArea(lnglats[0])

				// 		return new AMap.Polygon({
				// 			path: lnglats,
				// 			fillOpacity: 0.2, //1 - Math.sqrt(area / 8000000000), // 面积越大透明度越高
				// 			strokeColor: '#63b2dc',
				// 			strokeWidth: 1,
				// 			fillColor: '#0aebff',
				// 		});
				// 	}
				// });
				// geojson.setMap(this.map);
				// //加载相关模型或图标
				// for (var i = 0; i < this.projectList.length; i++) {
				// 	var item = this.projectList[i];
				// 	var src = item.info.stand.indexOf('未达标') === -1 ? '/static/ydb.gif' : '/static/wdb.gif'
				// 	var color = item.info.stand.indexOf('未达标') === -1 ? [0.23529, 0.70196, 0.44314, 1] : [0.98039, 0.50196, 0.44706,
				// 		1
				// 	]
				// 	//加载图标和windowInfo
				// 	this.zhengli_loadPoints(item.position[0], item.position[1], src, 200, item.info, color)
				// }
			},

			//外部模型加载函数
			/*
					lng: 经度
					lat: 纬度
					fileName: 加载的模型文件名
					rotate: 模型旋转角度（主要是给塔机用的）
					jindu: 模型进度
					scale: 模型缩放
				*/
			zhengli_loadModel(lng, lat, fileName, rotate, jindu, scale) {
				var objLoader = new THREE.OBJLoader2();
				var callbackOnLoad = event => {
					this.object = event.detail.loaderRootNode;

					this.modelsList.push(this.object);
					try {

					} catch (err) {

					}
					this.object3Dlayer = new AMap.Object3DLayer();
					var meshes = event.detail.loaderRootNode.children;
					for (var i = 0; i < meshes.length; i++) {
						var vecticesF3 = meshes[i].geometry.attributes.position;
						var vecticesNormal3 = meshes[i].geometry.attributes.normal;
						var vecticesUV2 = meshes[i].geometry.attributes.uv;
						var vectexCount = vecticesF3.count;
						var mesh = new AMap.Object3D.MeshAcceptLights();
						var geometry = mesh.geometry;
						//底部一圈
						// debugger
						var c, opacity;
						var material = meshes[i].material[0] || meshes[i].material;

						if (material.map && material.map.image) {
							mesh.textures.push(material.map.image.currentSrc);
							// mesh.textures.push('https://a.amap.com/jsapi_demos/static/demo-center/model/1519/1519.bmp');
							// mesh.textures.push('/static/' + material.map.image.currentSrc.split('/static/')[1]);
						}

						c = material.color;
						material.opacity = jindu;
						material.normalScale.x = 0.1;
						opacity = material.opacity;
						// debugger
						for (var j = 0; j < vectexCount; j += 1) {
							var s = j * 3;
							geometry.vertices.push(vecticesF3.array[s], vecticesF3.array[s + 2], -vecticesF3.array[s + 1]);

							if (vecticesNormal3) {
								geometry.vertexNormals.push(vecticesNormal3.array[s], vecticesNormal3.array[s + 2], -vecticesNormal3.array[s +
									1]);
							}
							if (vecticesUV2) {
								geometry.vertexUVs.push(vecticesUV2.array[j * 2], 1 - vecticesUV2.array[j * 2 + 1]);
							}
							geometry.vertexColors.push(c.r, c.g, c.b, opacity);
						}
						// debugger
						mesh.DEPTH_TEST = material.depthTest;
						// mesh.backOrFront = 'both'
						mesh.transparent = opacity < 1;
						mesh.scale(scale, scale, scale);
						//旋转
						mesh.rotateZ(rotate);
						mesh.position(new AMap.LngLat(lng, lat));
						this.object3Dlayer.add(mesh);
						this.map.add(this.object3Dlayer);
					}
					//点击模型触发方法，暂时没用，后续添加
					// this.map.on('click', ev => {
					// 	var pixel = ev.pixel;
					// 	var px = new AMap.Pixel(pixel.x, pixel.y);
					// 	var obj = this.map.getObject3DByContainerPos(px, [this.object3Dlayer], false) || {};

					// 	if (obj && obj.object) {
					// 		var a = meshes.find(item => {
					// 			return item.id === obj.object.id;
					// 		});
					// 		if (a) {
					// 			console.log(a);
					// 		}
					// 	}
					// });
				};
				objLoader.loadMtl(fileName + '.mtl', null, materials => {
					objLoader.setMaterials(materials);
					objLoader.load(
						fileName + '.obj',
						callbackOnLoad,
						res => {
							// this.build_progress = ((res.loaded / res.total) * 100).toFixed(0);
							//加载进度，暂时弃用，后续添加
						},
						null,
						null,
						false
					);
				});
			},
			//加载气球（主要展示摄像头））
			zhengli_loadPoints(lng, lat, picUrl, height, info, colorArr) {
				var self = this;

				function lnglatToG20(lnglat) {
					lnglat = self.map.lngLatToGeodeticCoord(lnglat);
					lnglat.x = AMap.Util.format(lnglat.x, 3);
					lnglat.y = AMap.Util.format(lnglat.y, 3);
					return lnglat;
				}
				var jwd = [lng, lat];
				var lines = new AMap.Object3D.Line();
				var lineGeo = lines.geometry;
				var center = lnglatToG20(jwd);
				var points3D = new AMap.Object3D.RoundPoints();
				var pointsGeo = points3D.geometry;
				var object3Dlayer = new AMap.Object3DLayer({
					zIndex: 400,
					opacity: 1
				});
				points3D.transparent = true;
				// 连线
				// lineGeo.vertices.push(center.x, center.y, 0);
				// lineGeo.vertexColors.push(0, 1, 1, 1);
				// lineGeo.vertices.push(center.x, center.y, -height);
				// lineGeo.vertexColors.push(0, 1, 1, 1);
				pointsGeo.vertices.push(center.x, center.y, 0); // 尾部小点
				pointsGeo.pointSizes.push(16);
				pointsGeo.vertexColors.push(colorArr[0], colorArr[1], colorArr[2], 0.8); //color="#3dd5a7"
				points3D.borderColor = [colorArr[0], colorArr[1], colorArr[2], 0.3];
				points3D.borderWeight = 4;
				object3Dlayer.add(lines);
				object3Dlayer.add(points3D);
				this.line3DList.push(object3Dlayer);
				this.map.add(object3Dlayer);
				var jiankong = new AMap.Marker({
					icon: picUrl,
					offset: new AMap.Pixel(-12.5, -60),
					position: [lng, lat],
					map: this.map,
					height: height
				});
				jiankong.on('click', ev => {
					this.zhengli_mapViewInfo(lng, lat, height, info)
				});

				this.map.setFitView();

			},
			//地图里面的窗口
			zhengli_mapViewInfo(lng, lat, height, info) {
				this.projectInfo = info;
				this.infoWindow = new AMap.InfoWindow({
					isCustom: true, //使用自定义窗体
					content: this.$refs.infoWindowRef.$el
				});
				this.infoWindow.open(this.map, [lng, lat], height - 100);
				this.$store.state.showWoindow = true
			},
			close() {
				this.infoWindow.close();
			},
			gundong() {
				var cur = 0;
				this.jsq = setInterval(() => {
					this.close();
					this.projectList[cur].visible = true;
					if (cur === this.projectList.length) {
						cur = 0;
					} else {
						cur += 1;
					}
				}, 3000);
			},
			stopGd() {
				clearInterval(this.jsq);
				this.jsq = null;
			}
		}
	};
</script>

<style lang="css">
	.container {
		width: 100%;
		height: calc(100% + 22px);
		position: relative;
		overflow: hidden;
		/* transform: scale(2.3); */
		/* z-index: -1; */
	}

	.amap-box {
		/* transform: scale(1.6); */
	}

	#amapBox3d {
		width: 100%;
		height: calc(100% + 22px);
		position: relative;
		overflow: hidden;
	}
</style>
